package com.example.dishit.view.editpref;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Switch;

import com.example.dishit.R;
import com.example.dishit.controller.editpref.EditPrefController;
import com.example.dishit.controller.editpref.IEditPrefController;
import com.example.dishit.model.editpref.PreferenceData;

public class EditPrefActivity extends Activity implements IEditPrefView {
    private IEditPrefController controller;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_pref);
        
        // Create "Edit Preferences" controller.
        controller = new EditPrefController(this);
        
        // Draw the currently-stored preferences.
        final PreferenceData preferences = controller.getPreferences();
        draw(preferences);
    }
    
    private void draw(final PreferenceData preferences) {
        // ALERTS FROM MY DISHERS
        final Switch alertsFromDishersButton = (Switch)findViewById(R.id.disher_alerts_switch);
        alertsFromDishersButton.setChecked(preferences.isAlertsFromDishersEnabled());
        alertsFromDishersButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                controller.savePreferences(getDisplayedPreferences());
            }
        });
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_edit_pref, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.done_edit_pref_button:
                controller.cancel();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    private PreferenceData getDisplayedPreferences() {
        final PreferenceData.Builder builder = new PreferenceData.Builder();
        
        // ALERTS FROM MY DISHERS
        final Switch alertsFromDishersButton = (Switch)findViewById(R.id.disher_alerts_switch);
        final boolean isAlertsFromDishersEnabled = alertsFromDishersButton.isChecked();
        builder.alertsFromDishersEnabled(isAlertsFromDishersEnabled);
        
        return builder.build();
    }
}
